﻿using Base;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace WebApp.Filter
{
    public class SignFilter : ActionFilterAttribute
    {

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            var noNeedCheck = false;
            if (context.ActionDescriptor is ControllerActionDescriptor controllerActionDescriptor)
            {
                noNeedCheck = controllerActionDescriptor.MethodInfo.GetCustomAttributes(inherit: true)
                  .Any(a => a.GetType().Equals(typeof(NoSignAttribute)));
            }
            if (noNeedCheck) return;

            string id = context.HttpContext.User.FindFirstValue(SystemConst.CURRENT_ADMIN_ID);


            //var identity = new ClaimsIdentity(CookieAuthenticationDefaults.AuthenticationScheme);
            //// 检查登陆 - 在SignIn中判断用户合法性，将登陆信息保存在Session中，在SignOut中移除登陆信息
            //// 获取登陆信息 - 这里采用Session来保存登陆信息 -- Constants是字符串常量池
            ////var admin = identity.Claims.Where(x => x.Type == SystemConst.CURRENT_ADMIN).Select(x=>x.Value).FirstOrDefault();
            //var id = identity.Claims.Where(x => x.Type == SystemConst.CURRENT_ADMIN_ID).Select(x => x.Value).FirstOrDefault();


            //// 检查登陆信息
            if (string.IsNullOrEmpty(id))
            {
                // 用户未登陆 - 跳转到登陆界面
                context.Result = new RedirectResult("/Home/Login");
            }
            base.OnActionExecuting(context);

        }

    }

    public class NoSignAttribute : ActionFilterAttribute { }

}
